<template>
    <div class="app-content">
        <div class="box" id="box" ref="box">
            <!-- diy控件 -->
            <!-- {{pageList[util.findIndex(pageList,pageOnlyId)]}} -->
            <div class="box-top">
                <div v-for="item in controls" :key="item.id" @click.stop="moduleClick(item)" >
                    <NavBar v-if="item.isShow && item.type == -1" :base="item.base" :text="item.text"/>
                    <GlobalStyle v-if="item.isShow && item.type == -2" :base="item.base" :item="item"/>
                </div>
            </div>
            
            <!-- diy模块 -->
            <!-- <div class="box-con" id="content" ref="content" :style="{padding: style.pd.is ? `0 ${style.pd.rn}px 0 ${style.pd.ln}px` : '0 0 0 0'}"> -->
            <div class="box-con" id="content" ref="content" :style="[globalStyle.pd]">
                <div class="drag-box" v-if="showDragBox" @dragenter="dragenter" @dragleave="dragleave" @dragover="dragover" @drop="drop" data-id="first">放在这里</div>
                <draggable class="list-group" tag="ul" v-model="newDiyModule" v-bind="dragOptions" @start="dragStart" @end="dragEnd">
                    <div
                        class="item"
                        :class="{'item_border': attributes.id === item.id}"
                        v-for="(item, index) in diyModule"
                        :key="item.id"
                        @click.stop="moduleClick(item)"
                        :ref="`r-${item.id}`"
                        :data-id="item.id"
                        :style="[globalStyle.mb]"
                    >
                        <p class="p" v-if="drag">{{(item.title && item.title.t) || item.name}}</p>
                        <template v-else>
                            <Navigate :base="item.base" :list="item.list" :index="index" v-if="item.type == 1"/>
                            <ImageText :base="item.base" :content="item.content" :title="item.title" :index="index" v-if="item.type == 2"/>
                        </template>
                        <div class="drag-box" v-if="showDragBox" @dragenter="dragenter" @dragleave="dragleave" @dragover="dragover" @drop="drop" :data-id="index">放在这里</div>
                    </div>
                </draggable>
            </div>
        </div>
    </div>
</template>

<script>
import { mapState } from 'vuex'
import NavBar from './module/nav_bar';
import GlobalStyle from './module/global_style';

import Navigate from './module/navigate';
import ImageText from './module/image_text';

import draggable from 'vuedraggable'
import $ from 'jquery'
export default {
    components:{ NavBar, GlobalStyle, Navigate, ImageText, draggable },
    data() {
        return {
            list:[],
            drag: false
        }
    },
    computed:{
		...mapState(['pageList','pageOnlyId','diyModule','controls','isAddModule','showDragBox', 'attributes', 'isRevoke', 'historyIndex']),
        dragOptions() {
            return {
                animation: 200,
                group: "description",
                disabled: false,
                ghostClass: "ghost"
            };
        },
        newDiyModule:{
            get(){
                return this.diyModule
            },
            set(arr){
                this.$store.commit('dragDiyModule',arr)
            }
        },
        globalStyle(){
            let style = {
                mb: {},
                pd: {}
            },
                control = this.controls.filter(item => item.type === -2)[0],
                pd = {},
                mb = {};
            control && (
                pd = control.pd,
                mb = control.mb,
                mb.is && (
                    style.mb.marginTop = `${mb.num}px`
                ),
                pd.is && (
                    style.pd.padding = `0 ${pd.rn}px 0 ${pd.ln}px`
                )
            )
            return style
        }
    },
    watch:{
        isAddModule(v){
            if(v){
                var scrollHeight = this.$refs.content.scrollHeight
                this.$nextTick(()=>{
                    $('#content').animate({scrollTop:scrollHeight}, 300)
                    this.$store.commit('isAddModule', false)
                })
            }
        },
        diyModule: {
            handler: function (newVal) {
                if(this.isRevoke){
                    // 记录变化之前先判断 是否有撤销行为 如果有则从当前显示的那里开始记录历史
					if(this.historyIndex != -1){ // 此时说明在撤销内的其中一步
                        this.$store.commit('recordMiddleHistory')
					}
                    let data = JSON.parse(JSON.stringify(newVal))
                    this.$store.commit('recordHistory', data)
                }
			},
			deep: true
        }
    },
    methods: {
        
        moduleClick(item){
            // console.log(item)
            this.$store.dispatch('pushAttr',item)   // 存入需要编辑的属性
            this.$store.commit('toggleAttr', true)  // 打开属性面板
        },
        // diy模块 拖动开始关闭 属性设置面板
        dragStart(e){
            this.drag = true
            localStorage.setItem('id', e.item.getAttribute('data-id'))
            this.$store.commit('toggleAttr', false)
        },
        dragEnd(){
            this.drag = false
            setTimeout(() => {
                let id = localStorage.getItem('id'), offsetTop = 0;
                offsetTop = this.$refs[`r-${id}`][0].offsetTop
                // console.log(`当前元素距离顶部的距离：${offsetTop}`)
                $('#content').animate({scrollTop: offsetTop - 10}, 500)
                localStorage.removeItem('id')
            }, 300);
        },
        // 拖动元素进入div时触发
        dragenter(event){
            if ( event.target.className == "drag-box" ) {
                event.target.style.opacity = "1";
            }
        },
        // 拖动元素离开div时触发
        dragleave(event){
            if ( event.target.className == "drag-box" ) {
                event.target.style.opacity = "0.4";
            }
        },
        // 默认情况下,数据/元素不能在其他元素中被拖放。对于drop我们必须防止元素的默认处理
        dragover(event){
            event.preventDefault()
        },
        // 利用dataTransfer.getData()方法获得拖放数据
        drop(event){
            event.preventDefault();
            let item = event.dataTransfer.getData("text"), index = event.target.dataset.id
            console.log(event.target.dataset)
            this.$store.commit('insertDiyModule',{index, item})
        }
    },
}
</script>

<style lang="scss" scoped>
.app-content{flex: 1;display: flex;align-items: center;padding-left: 50px;padding-right: 30px;
    .box{width: 375px;height: 667px;background: #f3f3f3;box-shadow: 0px 0px 20px 0px #c6c6c67a;user-select: none;position: relative;//overflow-x: hidden;
        // .box-top{position: relative;z-index: 2;}
        .box-con{ height: calc(667px - 44px);overflow-x: hidden;position: relative;z-index: 2;
            &::-webkit-scrollbar { width: 1px;height: 3px; }
            .item{position: relative;
                &:hover>::after{ clear: both;content: '';display: block;position: absolute;left: 0;right: 0;top: 0;bottom: 0;border: 1px dashed #409eff;box-shadow: inset 0 0 10px rgba($color: #409eff, $alpha: .2);z-index: 2; }
                &_border{
                    &>::after{ clear: both;content: '';display: block;position: absolute;left: 0;right: 0;top: 0;bottom: 0;border: 1px dashed #409eff;z-index: 2; }
                }
                & > .p{line-height: 50px;font-size: 18px;text-align: center;background: #fff;margin-top: 10px;}
            }
            .border{border: 1px dashed #409eff !important}

            .drag-box{text-align: center;line-height: 80px;height: 80px;margin: 10px 0;border: 1px dashed #409eff;background: rgba($color: #409eff, $alpha: .2);color: #409eff;font-size: 14px;opacity: 0.4;
                &-active{opacity: 1;}
            }
        }
    }
}
</style>
